package com.kamistoat.meimeimall.meimeimallproduct.service.impl;


import com.kamistoat.meimeimall.common.constant.DatabaseConstant;
import com.kamistoat.meimeimall.common.utils.PageUtils;
import com.kamistoat.meimeimall.common.utils.Query;
import com.kamistoat.meimeimall.meimeimallproduct.dao.CategoryBrandRelationDao;
import com.kamistoat.meimeimall.meimeimallproduct.dao.CategoryDao;
import com.kamistoat.meimeimall.meimeimallproduct.entity.CategoryBrandRelationEntity;
import com.kamistoat.meimeimall.meimeimallproduct.service.CategoryBrandRelationService;
import com.kamistoat.meimeimall.meimeimallproduct.dao.BrandDao;
import com.kamistoat.meimeimall.meimeimallproduct.entity.BrandEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.kamistoat.meimeimall.meimeimallproduct.service.BrandService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    BrandDao brandDao;

    @Autowired
    CategoryDao categoryDao;
    @Autowired
    CategoryBrandRelationDao categoryBrandRelationDao;
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    /**
     * 分页查询方法，注意QueryWrapper是空的，说明没有查询条件
     * 我们希望和之前一样，接收查询关键字Key进行模糊查询
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        // 从前端提交的params中获取出关键字key
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> queryWrapper = new QueryWrapper<BrandEntity>();
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((obj) -> {
                obj.eq("brand_id", key).or().eq("descript", key).or().eq("name", key);
            });
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 我们自己编写的方法
     * 一并更新所有冗余存储的数据表
     *
     * @param brand 传来的Entity
     */
    @Override
    @Transactional
    public void updateDetail(BrandEntity brand) {
        // 首先先更新brand数据表本身
        this.updateById(brand);
        // 保证冗余字段的数据保持同步
        if (!StringUtils.isEmpty(brand.getName())) {
            // 目前存在的冗余字段只有brandName。所以先判断是否为空，如果不为空，就意味着要一并修改其他数据表中的冗余字段
            // 注意，并不是在这个方法里进行冗余更新，而是在这里调用冗余字段所在的service，让冗余字段所在的service执行更新
            // 传递的参数也不是BrandEntity，因为冗余字段所在的是CategoryBrandRelationEntity，只传递有用的信息就行了
            categoryBrandRelationService.updateCBRelation_Brand(brand.getBrandId(), brand.getName());
        }
        // TODO  如果有其他引用了brand字段的地方，还需要更新其他冗余字段
    }

    /**
     * 获取品牌名称
     *
     * @param brandId
     * @return
     */
    @Override
    public String getBrandName(Long brandId) {
        BrandEntity one = this.getOne(new QueryWrapper<BrandEntity>().select("name").eq("brand_id", brandId));
        if (one != null) {
            return one.getName();
        }
        return "";
    }

    /**
     * 生成品牌测试数据
     *
     * @param brandNum
     */
    @Override
    public void constructTestBrandData(Integer brandNum) {
        List<Long> allCategoryIds = categoryDao.selectAllThirdCategoryId();
        int categoryNum = allCategoryIds.size();

        List<BrandEntity> brandEntities = new ArrayList<>();
        List<CategoryBrandRelationEntity> relationEntities = new ArrayList<>();
        for (int index = 0; index < brandNum; index++) {
            BrandEntity brandEntity = new BrandEntity();
            brandEntity.setName("测试品牌" + (index + 1));
            brandEntity.setDescript("测试品牌" + (index + 1) + "详情");
            brandEntity.setLogo("测试品牌" + (index + 1) + "图标");
            brandEntity.setFirstLetter("C");
            brandEntity.setShowStatus(0);
            brandEntity.setCreateTime(new Date());
            brandEntity.setUpdateTime(new Date());
            brandEntity.setDelete(DatabaseConstant.UN_LOGISTIC_DELETED);
            brandEntities.add(brandEntity);
        }
        brandDao.insertBatch(brandEntities);

        for (BrandEntity brandEntity : brandEntities) {
            int randomCate1 = (int) (Math.random() * (categoryNum));
            CategoryBrandRelationEntity relation1 = new CategoryBrandRelationEntity();
            relation1.setBrandId(brandEntity.getBrandId());
            relation1.setCatelogId(allCategoryIds.get(randomCate1));
            relation1.setBrandName(brandEntity.getName());
            relation1.setCatelogName("测试");
            relation1.setCreateTime(new Date());
            relation1.setUpdateTime(new Date());
            relation1.setDelete(DatabaseConstant.UN_LOGISTIC_DELETED);
            relationEntities.add(relation1);

            int randomCate2 = (int) (Math.random() * (categoryNum));
            CategoryBrandRelationEntity relation2 = new CategoryBrandRelationEntity();
            relation2.setBrandId(brandEntity.getBrandId());
            relation2.setCatelogId(allCategoryIds.get(randomCate2));
            relation2.setBrandName(brandEntity.getName());
            relation2.setCatelogName("测试");
            relation2.setCreateTime(new Date());
            relation2.setUpdateTime(new Date());
            relation2.setDelete(DatabaseConstant.UN_LOGISTIC_DELETED);
            relationEntities.add(relation2);
        }
        categoryBrandRelationDao.insertBatch(relationEntities);
    }

}